<!-- 商品详情 -->
<template>
    <div>
        <el-button type="primary" @click="submitForm('gooItem')">提交</el-button>
        <!-- <el-button @click="getCateSearchValue">取消</el-button> -->
        <!-- <el-button @click="resetForm('gooItem')">重置</el-button> -->
        <div style="border-style:solid;border-width:0.5px;border-color:#ccc;">

            <br>
            <el-form ref="gooItem" :rules="rules" :model="gooItem" label-width="120px">
                <el-form-item label="商品编号：">
                    <el-col :span="8">
                        <el-input placeholder="自动生成" v-model="gooItem.serialNumber" :disabled="true"> </el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="商品名：" prop="name">
                    <el-col :span="8">
                        <el-input v-model="gooItem.name"></el-input>
                    </el-col>
                </el-form-item>
                <!-- 类别:cate-search-object获取下拉选择；selected-cate-id处理默认选择 -->
                <el-form-item label="商品类别：" prop="cateId">
                    <CateSearch v-on:cate-search-object="getCateSearchValue" :selected-cate-id="gooItem.cateId"></CateSearch>
                </el-form-item>
                <el-form-item label="卖点：">
                    <el-col :span="4">
                        <el-input class="input-new-tag" v-if="inputSellPointVisable" v-model="inputSellPoint" ref="saveTagInput" size="mini" @keyup.enter.native="addOneSellPoint" @blur="addOneSellPoint">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showAddSellPoint">+ 卖点</el-button>
                    </el-col>
                    <el-col :span="18">
                        <el-tag type="primary" :key="tag" v-for="tag in gooItem.sellPoint" :closable="true" :close-transition="false" @close="removeOnePoint(tag)">
                            {{tag}}
                        </el-tag>
                    </el-col>
                </el-form-item>

                <el-form-item label="库存数量：">
                    <el-col :span="4">
                        <el-form-item prop="count">
                            <el-input-number v-model="gooItem.count" :min=1 size="small"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="定价(元)：" prop="originPrice">
                            <el-input-number v-model="gooItem.originPrice" :min=0 size="small"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="售价(元)：" prop="sellPrice">
                            <el-input-number v-model="gooItem.sellPrice" :min=0 size="small"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-form-item>

                    <!--       :multiple="true" 多选  
                     :on-remove="attashRemove" //文件移除
                     -->
                  <el-form-item label="附件: ">
                    <el-upload :action="baseResUpUrl" name="files" 
                        list-type="picture-card" 
                        :file-list="picList"
                        :on-preview="attashPreview" 
                        :on-success="attashUpload" 
                        :on-remove="handleRemove"
                        :before-upload="validUpload" >
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog v-model="dialogVisible" size="tiny">
                        <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import CateSearch from "../sys-setting/CateSearch";
import gooItemApi from "../../api/gooItemApi";
import { commonApi } from '../../api/api'
import Store from "../../utils/storage.js";
export default {
  data: function() {
    var checkCount = (rule, value, callback) => {
      console.log("check count");
      if (!value) {
        return callback(new Error("库存数量不能为空"));
      } else if (value < 0 || value > 100000) {
        return callback(new Error("库存数量保持在[0]到[100000]之间"));
      } else {
        var arr = value.toString().split(".");
        if (arr.length > 1) {
          return callback(new Error("库存数量只能是整数"));
        } else {
          callback();
        }
      }
    };
    var checkPrice = (rule, value, callback) => {
      if (!value && value != 0) {
        return callback(new Error("金额不能为空"));
      } else if (value < 0 || value > 100000000) {
        return callback(new Error("金额保持在[0]到[100000000]之间"));
      } else {
        var arr = value.toString().split(".");
        if (arr.length > 1 && arr[1].length > 2) {
          return callback(new Error("金额只能保留两位小数位数"));
        } else {
          callback();
        }
      }
    };
    return {
      baseResDownUrl: null,//资源获取路径
      baseResUpUrl: null,//资源上传路径
      inputSellPointVisable: false, //卖点输入框是否可见
      inputSellPoint: "", //增加一个信息的卖点
      dialogImageUrl: "", //附件，预览
      dialogVisible: false,
      picList: [], // 附件列表
      gooItem: {
        id: null,
        serialNumber: null,
        name: null,
        attashments: [],
        cateId: null,
        cateName: null,
        sellPoint: [],
        count: 0,
        sellPrice: 0.0,
        originPrice: 0.0,
        status: null,
        itemDesc: null,
        createdDate: null,
        updatedDate: null
      },

      rules: {
        name: [
          { required: true, message: "[商品名]不能为空", trigger: "blur" },
          { min: 1, max: 16, message: "[商品名]保持在[1]到[16]个字符", trigger: "blur" }
        ],
        cateId: [{ required: true, message: "[商品类别]不能为空" }],
        count: [{ validator: checkCount, trigger: "blur" }],
        originPrice: [{ validator: checkPrice, trigger: "blur" }],
        sellPrice: [{ validator: checkPrice, trigger: "blur" }]
      }
    };
  },

  components: {
    CateSearch
  },
  props: {
    gooItemId: Number
  },
  created: function() {
    this.baseResDownUrl = commonApi.retrieveFileUrl('');
    this.baseResUpUrl = commonApi.uploadFilesUrlCompress(270,240);
    const goo = Store.fetch("goo-item");
    console.log(goo);
    if (goo != null && goo != "") {
      this.gooItem = goo;
      let _atsh = this.gooItem.attashments;//回显附件图片
      if (_atsh) {
        for (let i in _atsh) {
          this.picList.push({
            name: _atsh[i],
            url: this.baseResDownUrl + _atsh[i]
          });
        }
      }
    }
  },
  methods: {
    loadData(gooItemId) {
      console.log("加载商品数据:" + gooItemId);
      if (gooItemId) {
        gooItemApi
          .getOne(gooItemId)
          .then(res => {
            if (res.status == 200 && res.data != "") {
              this.gooItem = res.data;
            }
          })
          .catch(err => {
            this.$notify.error({
              title: "获取内容失败",
              message: err.errors_msg
            });
          });
      }
    },
    getCateSearchValue(obj) {
      //组件商品类别的选择
      if (obj) {
        this.gooItem.cateId = obj.id;
        this.gooItem.cateName = obj.name;
      }
    },
    removeOnePoint(tag) {
      var sellPoints = this.gooItem.sellPoint;
      sellPoints.splice(sellPoints.indexOf(tag), 1);
    },
    showAddSellPoint() {
      this.inputSellPointVisable = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    addOneSellPoint() {
      let inputSellPoint = this.inputSellPoint;
      const _sellPoint = this.gooItem.sellPoint;
      if (!_sellPoint) {
           this.gooItem.sellPoint = [];
      }
      if (inputSellPoint) {
        if(inputSellPoint.length>=16) {
          this.$notify({title: "提示",message: "卖点有必要这么长嘛",type: "warning"})
          return false;
        }
        if(_sellPoint.length>=5) {
          this.$notify({title: "提示",message: "卖点有点多呀",type: "warning"})
          this.inputSellPoint = "";
          return false;
        }
        _sellPoint.push(inputSellPoint);
      }
      this.inputSellPointVisable = false;
      this.inputSellPoint = "";
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    attashPreview(file) {
      //预览照片
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    attashUpload(response, file, fileList) {
      this.picList = fileList;
    },
    handleRemove(file, fileList) {
        this.picList = fileList;
        console.log('删除一张图片:',fileList)
    },
    validUpload(file) {
      let _size = this.picList.length | 0;
      if (_size === 6) {
        this.$notify({
          title: "提示",
          message: "您最多只能上传5张图片",
          type: "warning"
        });
        return false;
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let formData = this.gooItem;
          let _pics = this.picList;
          console.log('表单附件',_pics)
          if (_pics) {
            formData.attashments=[];
            for (let i in _pics) {
              console.log("pic", _pics[i]);
              if(_pics[i].response) {
                formData.attashments.push(_pics[i].response[0]);
              }else {
                 formData.attashments.push(_pics[i].name);
              }
            }
          }
          console.log('当前表单附件：',formData.attashments)
          let isAdd = formData.id == null ? true : false;
          if (isAdd) {
            gooItemApi
              .addOne(formData)
              .then(res => {
                if (res.status == 200) {
                  this.$notify({
                    title: "成功",
                    message: "新增成功",
                    type: "success"
                  });
                  this.gooItem = res.data;
                  this.$emit("retrieve-cur-step", 1);
                  this.$store.dispatch("doSaveGooItem", res.data);
                  console.log(this.$store.state.gooItem);
                }
              })
              .catch(err => {
                this.$notify.error({
                  title: " 操作失败",
                  message: err.errors_msg
                });
              });
          } else {
            console.log("update");
            gooItemApi
              .updateOne(formData.id, formData)
              .then(res => {
                if (res.status == 200) {
                  this.$notify({
                    title: "成功",
                    message: "修改成功",
                    type: "success"
                  });
                  this.gooItem = res.data;
                  this.$emit("retrieve-cur-step", 1);
                  this.$store.dispatch("doSaveGooItem", this.gooItem);
                }
              })
              .catch(err => {
                this.$notify.error({
                  title: " 操作失败",
                  message: err.errors_msg
                });
              });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
